package com.tiancheng.trade.payment.channel.apple;

import com.alibaba.fastjson.JSONObject;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.payment.channel.bo.AppleNotifications;
import com.tiancheng.trade.payment.channel.bo.AppleSignedTransactionInfo;
import com.tiancheng.trade.payment.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.Map;

/**
 * 苹果支付渠道工具类
 *
 * @Author: likailun
 * @Description:
 * @Date: create in 2022/6/17 3:51 下午
 */
@Slf4j
public class AppleUtils {
    public static Map<String, Object> appleMsgHandler(String signedPayload) {
        //Base64 解码
        signedPayload = JwtUtils.verifyNew(signedPayload);
        if (StringUtils.isEmpty(signedPayload)) {
            log.error("苹果消息通知，Jwt验证失败");
            return null;
        }
        final JSONObject msgBody = JSONObject.parseObject(signedPayload);
        final JSONObject msgData = JSONObject.parseObject(msgBody.get("data").toString());

        String signedTransactionInfoStr = msgData.get("signedTransactionInfo").toString();
        //解密拿到数据
        String signedTransactionInfoDecode = JwtUtils.verifyNew(signedTransactionInfoStr);
        if (StringUtils.isEmpty(signedTransactionInfoDecode)) {
            log.error("苹果消息回调,验证数据异常");
            return null;
        }
        final AppleNotifications appleNotifications = new AppleNotifications();
        appleNotifications.setNotificationType(msgBody.getString("notificationType"));
        appleNotifications.setAppAppleId(msgData.getString("appAppleId"));
        appleNotifications.setBundleId(msgData.getString("bundleId"));
        appleNotifications.setBundleVersion(msgData.getString("bundleVersion"));
        appleNotifications.setEnvironment(msgData.getString("environment"));

        signedTransactionInfoDecode = signedTransactionInfoDecode.substring(signedTransactionInfoDecode.indexOf("{"), signedTransactionInfoDecode.lastIndexOf("}") + 1);
        final AppleSignedTransactionInfo appleSignedTransactionInfo = JSONObject.parseObject(signedTransactionInfoDecode, AppleSignedTransactionInfo.class);
        appleNotifications.setSignedTransactionInfo(appleSignedTransactionInfo);
        log.info("苹果订阅回调，解析完成，处理消息：{}", JsonUtil.toJsonString(appleNotifications));
        return JsonUtil.fromJson(JsonUtil.toJsonString(appleNotifications), Map.class);
    }
}
